<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { TableColumnsType, TableColumnType } from 'ant-design-vue'
import {
  Table as ATable,
  Card as ACard,
  Button as AButton,
  Input as AInput,
  Tag as ATag,
  Popconfirm as APopconfirm,
  message,
  Image as AImage,
  Tabs as ATabs,
  TabPane as ATabPane,
} from 'ant-design-vue'
import { SearchOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons-vue'
import {
  getPostList,
  getPostListByType,
  deletePost,
  updatePostStatus,
  searchPosts,
} from '@/api/manger'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

interface PostData {
  id: number
  authorId: number
  authorName: string | null
  authorAvatar: string | null
  title: string
  content: string
  type: number
  isAnonymous: number
  postStatus: number
  viewsCount: number
  commentsCount: number
  likesCount: number
  collectsCount: number
  createTime: string
  updateTime: string
  [key: `image${number}`]: string | null
}

interface PostType {
  text: string
  color: string
}

// 使用 Ant Design Vue 的内置类型
interface TableSlotScope {
  text: any
  record: Record<string, any> & PostData // 合并类型以确保兼容性
  index: number
  column: TableColumnType<PostData>
}

const loading = ref(false)
const dataSource = ref<PostData[]>([])
const searchText = ref('')
const router = useRouter()
const userStore = useUserStore()
const totalPosts = ref(0) // 添加总帖子数统计

// 修改帖子类型映射
const postTypes: Record<number, PostType> = {
  0: { text: '其他', color: '' },
  1: { text: '公告', color: 'red' },
  2: { text: '活动', color: 'blue' },
  3: { text: '求助', color: 'orange' },
  4: { text: '二手交易', color: 'green' },
  5: { text: '表白', color: 'pink' },
  6: { text: '失物招领', color: 'purple' },
  7: { text: '校园咨询', color: 'cyan' },
  8: { text: '吐槽', color: 'volcano' },
  9: { text: '学习', color: 'geekblue' },
  10: { text: '反馈与建议', color: 'gold' },
}

// 添加一个处理帖子状态的辅助函数
const getPostStatus = (status: number | null) => {
  // 当状态为 null 时返回 1 (正常)
  return status === null ? 1 : status
}

const columns: TableColumnsType<PostData> = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    width: 120,
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 200,
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'postStatus',
    width: 100,
  },
  {
    title: '互动数据',
    dataIndex: 'interaction',
    width: 280,
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 定义标签页类型
interface TabItem {
  id: number
  name: string
}

// 修改标签页数据，确保顺序一致
const tabs: TabItem[] = [
  { id: 0, name: '综合' },
  { id: 1, name: '公告' },
  { id: 2, name: '活动' },
  { id: 3, name: '求助' },
  { id: 4, name: '二手交易' },
  { id: 5, name: '表白' },
  { id: 6, name: '失物招领' },
  { id: 7, name: '校园咨询' },
  { id: 8, name: '吐槽' },
  { id: 9, name: '学习' },
  { id: 10, name: '反馈与建议' },
  { id: 0, name: '其他' },
]

const activeTab = ref(0) // 当前选中的标签页

// 修改获取帖子列表的方法
const fetchPostList = async (typeId?: number) => {
  try {
    loading.value = true
    const res = await (typeId === undefined ? getPostList() : getPostListByType(typeId))
    if (res.data.code === 200) {
      dataSource.value = res.data.data
      totalPosts.value = res.data.data.length // 更新总帖子数
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    message.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabChange = (key: string) => {
  const typeId = parseInt(key)
  activeTab.value = typeId
  fetchPostList(typeId === 0 ? undefined : typeId)
}

// 修改搜索方法
const handleSearch = async () => {
  if (!searchText.value.trim()) {
    // 如果搜索框为空，恢复显示所有帖子
    fetchPostList(activeTab.value === 0 ? undefined : activeTab.value)
    return
  }

  const currentUserId = userStore.userInfo?.id
  if (!currentUserId) {
    message.error('用户信息获取失败')
    return
  }

  try {
    loading.value = true
    const res = await searchPosts(searchText.value.trim(), currentUserId)
    if (res.data.code === 200) {
      // 只使用返回的帖子数据
      dataSource.value = res.data.data.posts
      totalPosts.value = res.data.data.posts.length
      // 清除标签页选中状态
      activeTab.value = 0
    }
  } catch (error) {
    console.error('搜索失败:', error)
    message.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 添加清除搜索的方法
const handleClearSearch = () => {
  searchText.value = ''
  fetchPostList(activeTab.value === 0 ? undefined : activeTab.value)
}

// 添加类型断言函数
const asPostData = (record: Record<string, any>): PostData => {
  return record as PostData
}

const handleView = (record: Record<string, any>) => {
  const postData = asPostData(record)
  router.push(`/post/${postData.id}`)
}

const handleDelete = async (record: Record<string, any>) => {
  const postData = asPostData(record)
  const currentUserId = userStore.userInfo?.id

  if (!currentUserId) {
    message.error('用户信息获取失败')
    return
  }

  try {
    loading.value = true
    const res = await deletePost(postData.id, currentUserId)
    if (res.data.code === 200) {
      message.success('删除成功')
      fetchPostList(activeTab.value === 0 ? undefined : activeTab.value)
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error: any) {
    console.error('删除帖子失败:', error)
    message.error(error.response?.data?.message || '删除帖子失败')
  } finally {
    loading.value = false
  }
}

const handleStatusChange = async (record: Record<string, any>) => {
  const postData = asPostData(record)
  try {
    loading.value = true
    const newStatus = getPostStatus(postData.postStatus) === 1 ? 0 : 1
    const res = await updatePostStatus(postData.id, newStatus)
    if (res.data.code === 200) {
      message.success(`${newStatus === 1 ? '启用' : '禁用'}成功`)
      fetchPostList()
    }
  } catch (error) {
    console.error('更新帖子状态失败:', error)
    message.error('更新帖子状态失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchPostList()
})
</script>

<template>
  <div class="post-manager">
    <ACard class="search-card">
      <div class="search-form">
        <AInput
          v-model:value="searchText"
          placeholder="搜索帖子标题/内容"
          allow-clear
          @pressEnter="handleSearch"
          @clear="handleClearSearch"
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </AInput>
        <AButton type="primary" @click="handleSearch">搜索</AButton>
        <div class="total-posts">
          总帖子数：<span class="total-number">{{ totalPosts }}</span>
          <template v-if="searchText"> (搜索结果) </template>
        </div>
      </div>
    </ACard>

    <ACard class="table-card">
      <!-- 添加标签页 -->
      <ATabs v-model:activeKey="activeTab" class="post-tabs" @change="handleTabChange">
        <ATabPane v-for="tab in tabs" :key="tab.id" :tab="tab.name" />
      </ATabs>

      <ATable
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :scroll="{ x: 1500 }"
        :row-key="(record: PostData) => record.id"
      >
        <template #bodyCell="scope">
          <template v-if="scope.column.dataIndex === 'authorName'">
            <div class="author-cell">
              <AImage
                :src="scope.record.authorAvatar || '/default-avatar.png'"
                :fallback="'/default-avatar.png'"
                :width="32"
                :height="32"
                :preview="false"
                :style="{ borderRadius: '50%' }"
              />
              <span>{{ scope.record.isAnonymous ? '匿名用户' : scope.record.authorName }}</span>
            </div>
          </template>

          <template v-if="scope.column.dataIndex === 'type'">
            <ATag :color="postTypes[scope.text as number]?.color">
              {{ postTypes[scope.text as number]?.text || '未知' }}
            </ATag>
          </template>

          <template v-if="scope.column.dataIndex === 'postStatus'">
            <ATag :color="getPostStatus(scope.text) === 1 ? 'success' : 'error'">
              {{ getPostStatus(scope.text) === 1 ? '待审核' : '已发布' }}
            </ATag>
          </template>

          <template v-if="scope.column.dataIndex === 'interaction'">
            <div class="interaction-cell">
              <span>浏览: {{ scope.record.viewsCount }}</span>
              <span>评论: {{ scope.record.commentsCount }}</span>
              <span>点赞: {{ scope.record.likesCount }}</span>
              <span>收藏: {{ scope.record.collectsCount }}</span>
            </div>
          </template>

          <template v-if="scope.column.dataIndex === 'createTime'">
            {{ new Date(scope.text as string).toLocaleString() }}
          </template>

          <template v-if="scope.column.key === 'action'">
            <div class="action-cell">
              <AButton type="link" @click="handleView(scope.record)">
                <EyeOutlined />
                查看
              </AButton>
              <APopconfirm
                title="确定要删除这条帖子吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(scope.record)"
              >
                <AButton type="link" danger>
                  <DeleteOutlined />
                  删除
                </AButton>
              </APopconfirm>
              <APopconfirm
                :title="`确定要${getPostStatus(asPostData(scope.record).postStatus) === 1 ? '禁用' : '启用'}这条帖子吗？`"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleStatusChange(scope.record)"
              >
                <AButton
                  type="link"
                  :danger="getPostStatus(asPostData(scope.record).postStatus) === 1"
                >
                  {{ getPostStatus(asPostData(scope.record).postStatus) === 1 ? '禁用' : '启用' }}
                </AButton>
              </APopconfirm>
            </div>
          </template>

          <template v-if="scope.column.dataIndex === 'content'">
            <div class="content-cell">
              <p>{{ scope.record.content }}</p>
              <div v-if="scope.record.image1" class="image-preview">
                <template v-for="i in 9" :key="i">
                  <AImage
                    v-if="scope.record[`image${i}` as keyof PostData]"
                    :src="scope.record[`image${i}` as keyof PostData]"
                    :width="50"
                    :height="50"
                    style="margin-right: 8px; object-fit: cover"
                  />
                </template>
              </div>
            </div>
          </template>
        </template>
      </ATable>
    </ACard>
  </div>
</template>

<style scoped>
.post-manager {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  max-width: 800px; /* 增加宽度以适应新增内容 */
}

.table-card {
  min-height: 500px;
}

.author-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-cell {
  max-width: 300px;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.interaction-cell {
  display: flex;
  gap: 16px;
}

.action-cell {
  display: flex;
  gap: 8px;
}

:deep(.ant-table-cell) {
  vertical-align: top;
}

.post-tabs {
  margin-bottom: 24px;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 16px;
}

:deep(.ant-tabs-tab) {
  padding: 8px 16px;
}

:deep(.ant-tabs-tab-active) {
  font-weight: 500;
}

.total-posts {
  margin-left: auto; /* 将总数推到右侧 */
  font-size: 14px;
  color: #666;
}

.total-number {
  font-weight: bold;
  color: #1890ff;
  margin-left: 4px;
}
</style>
